package org.jing.ext.compress;

import org.jing.core.lang.JingException;

import java.io.File;
import java.io.FileInputStream;

/**
 * Description: 压缩包格式 <br>
 *
 * @author bks <br>
 * @since 2023-02-23 <br>
 */
public enum FileType {
    ZIP, TAR, SEVENZ, BZ2, GZ, RAR;

    /**
     * Description: 根据文件判断压缩格式 <br>
     *
     * @param file <br>
     * @return <br>
     */
    public static FileType fromFile(File file) {
        try (FileInputStream inputStream = new FileInputStream(file)) {
            byte[] buffer = new byte[2];
            if (-1 == inputStream.read(buffer)) {
                throw new JingException("failed to read head hex");
            }
            int headHex = 0;
            for (byte b : buffer) {
                headHex <<= 8;
                headHex |= b;
            }
            switch (headHex) {
                case 0x504B:
                    return FileType.ZIP;
                case 0x776f:
                    return FileType.TAR;
                case -0x51:
                    return FileType.SEVENZ;
                case 0x425a:
                    return FileType.BZ2;
                case -0x74:
                    return FileType.GZ;
                case 0x5261:
                    return FileType.RAR;
                default:
                    throw new JingException("unknown file compress type");
            }
        }
        catch (JingException e) {
            throw e;
        }
        catch (Throwable t) {
            throw new JingException(t);
        }
    }

    /**
     * Description: 根据文件判断压缩格式 <br>
     *
     * @param filePath <br>
     * @return <br>
     */
    public static FileType fromFile(String filePath) {
        return fromFile(new File(filePath));
    }
}
